<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KPI指标套餐管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei';
            background-color: #f5f5f5;
        }

        .container {
            height: 100vh;
            display: flex;
        }

        .main-panel {
            width: 100%;
            display: flex;
            flex-direction: column;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            text-align: center;
        }

        .header h1 {
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 300;
        }

        .header p {
            margin: 0;
            opacity: 0.9;
            font-size: 16px;
        }

        .content-wrapper {
            flex: 1;
            display: flex;
            gap: 10px;
            padding: 10px;
            overflow: hidden;
        }

        .left-panel {
            width: 300px;
            background: white;
            border-radius: 0px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
        }

        .right-panel {
            flex: 1;
            background: white;
            border-radius: 0px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
        }

        .indicator-library {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .selected-indicators {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
            /* 为子元素的定位提供参考 */
        }

        .selected-indicators .panel-content {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            padding-bottom: 120px;
            /* 为汇总区域和操作栏预留空间 */
            max-height: calc(100vh - 350px);
            /* 调整高度计算 */
        }

        .weight-summary {
            padding: 15px;
            background: #f8f9fa;
            border-top: 1px solid #e6e6e6;
            position: absolute;
            bottom: 60px;
            /* 为操作栏预留空间 */
            left: 0;
            right: 0;
            z-index: 10;
            box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
        }

        .action-bar {
            padding: 15px 20px;
            border-top: 1px solid #e6e6e6;
            background: #f8f9fa;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 11;
            /* 高于 weight-summary */
            box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
            height: 60px;
            /* 固定高度 */
            box-sizing: border-box;
        }

        .weight-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .weight-item:last-child {
            margin-bottom: 0;
        }

        .weight-total {
            font-weight: bold;
            color: #2c3e50;
            border-top: 1px solid #ddd;
            padding-top: 8px;
        }

        .weight-warning {
            color: #f56c6c;
        }

        .weight-valid {
            color: #67c23a;
        }

        .weight-summary-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
            /* 为绝对定位的action-bar提供参考 */
        }

        .weight-summary-content {
            background: #f8f9fa;
            border: 1px solid #e6e6e6;
            border-radius: 8px;
            padding: 20px;
            padding-bottom: 80px;
            /* 为底部action-bar预留空间 */
            overflow-y: auto;
            flex: 1;
        }

        .weight-summary-content .weight-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding: 12px;
            background: white;
            border-radius: 6px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            font-size: 14px;
        }

        .weight-summary-content .weight-item:last-child {
            margin-bottom: 0;
        }

        .weight-summary-content .weight-total {
            font-weight: bold;
            color: #2c3e50;
            border: 2px solid #409eff;
            background: #ecf5ff;
        }

        .action-bar {
            padding: 15px 20px;
            border-top: 1px solid #e6e6e6;
            background: #f8f9fa;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 10;
            box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
            height: 60px;
            box-sizing: border-box;
        }

        .user-management {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .panel-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            background-color: #F5F7FA;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .panel-header h3 {
            margin: 0;
            font-size: 18px;
            color: #2c3e50;
        }

        .panel-content {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            max-height: calc(100vh - 200px);
            /* 限制最大高度以确保滚动 */
        }

        .package-list {
            flex: 1;
            overflow-y: auto;
        }

        .package-item {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background-color 0.3s;
            position: relative;
        }

        .package-item:hover {
            background-color: #f5f7fa;
        }

        .package-item:hover .package-actions {
            opacity: 1;
        }

        .package-item.active {
            background-color: #ecf5ff;
            border-left: 3px solid #409eff;
        }

        .package-item:last-child {
            border-bottom: none;
        }

        .package-actions {
            position: absolute;
            top: 8px;
            right: 8px;
            opacity: 0;
            transition: opacity 0.3s;
            display: flex;
            gap: 5px;
        }

        .package-actions .el-button--small {
            padding: 4px 8px;
        }

        .package-name {
            font-weight: 500;
            color: #2c3e50;
            margin-bottom: 4px;
        }

        .package-remarks {
            font-size: 12px;
            color: #999;
            line-height: 1.4;
        }

        .package-sort {
            font-size: 10px;
            color: #666;
            float: right;
        }

        .add-package-btn {
            margin: 0;
        }

        .user-table {
            height: 300px;
        }

        .user-actions {
            margin-bottom: 15px;
        }



        .indicator-item {
            border: 1px solid #e6e6e6;
            border-radius: 6px;
            margin-bottom: 15px;
            background: white;
        }

        .indicator-title {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .indicator-name {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .chinese-name {
            font-weight: 500;
            color: #2c3e50;
            font-size: 14px;
        }

        .english-name {
            display: none;
            /* Hide English names to save space */
            font-size: 12px;
            color: #606266;
            font-style: italic;
        }

        .weight-input {
            width: 100px;
        }

        .weight-input .el-input-number__decrease,
        .weight-input .el-input-number__increase {
            width: 20px;
        }

        .weight-input .el-input__inner {
            text-align: center;
            font-weight: 500;
            padding-left: 8px;
            padding-right: 25px;
        }

        .sub-indicators {
            padding: 15px;
        }

        .sub-indicator-item:last-child {
            margin-bottom: 0;
        }



        .selected-major {
            border-left: 4px solid #409eff;
        }

        .selected-sub {
            background: #f0f9ff;
            border-color: #409eff;
        }

        .indicator-header {
            padding: 6px 15px;
            background: #f8f9fa;
            border-bottom: 1px solid #e6e6e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
            min-height: 32px;
            /* 与指标小类高度一致 */
        }

        .indicator-actions {
            display: flex;
            align-items: center;
            gap: 10px;
            min-width: 200px;
            /* 确保宽度一致 */
            visibility: hidden;
            /* 默认隐藏但保留空间 */
        }

        .selected-major .indicator-actions {
            visibility: visible;
            /* 选中时显示 */
        }

        .sub-indicator-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 6px 12px;
            border: 1px solid #f0f0f0;
            border-radius: 4px;
            margin-bottom: 6px;
            background: #fafafa;
            min-height: 32px;
            /* 减小高度 */
        }

        .sub-indicator-item .indicator-actions {
            min-width: 200px;
            /* 确保宽度一致 */
            visibility: hidden;
            /* 默认隐藏但保留空间 */
        }

        .sub-indicator-item.selected-sub .indicator-actions {
            visibility: visible;
            /* 选中时显示 */
        }



        .level-tag {
            font-size: 12px;
            padding: 2px 8px;
            border-radius: 4px;
        }

        .major-category {
            background-color: #f3e5f5;
            color: #7b1fa2;
            border: 1px solid #ce93d8;
        }

        .subcategory {
            background-color: #e8f5e8;
            color: #388e3c;
            border: 1px solid #a5d6a7;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container">
            <div class="main-panel">
                <!-- <div class="header">
                    <h1>KPI指标套餐管理</h1>
                    <p>创建和管理自定义指标套餐，从指标库中选择需要的指标并设置权重</p>
                </div> -->

                <div class="content-wrapper">
                    <!-- 左侧指标套餐管理面板 -->
                    <div class="left-panel">
                        <div class="panel-header">
                            <h3>指标套餐列表</h3>
                            <el-button type="primary" @click="showCreatePackageDialog" class="add-package-btn"
                                size="small">
                                <i class="el-icon-plus"></i> 新建套餐
                            </el-button>
                        </div>

                        <div class="package-list">
                            <el-empty v-if="packageList.length === 0" description="暂无套餐">
                            </el-empty>
                            <div v-for="pkg in sortedPackageList" :key="pkg.id" class="package-item"
                                :class="{ active: currentPackage && currentPackage.id === pkg.id }"
                                @click="selectPackage(pkg)">
                                <div class="package-name">
                                    {{ pkg.name }}
                                </div>
                                <div class="package-remarks" v-if="pkg.remarks">
                                    {{ pkg.remarks }}
                                </div>
                                <div class="package-actions" @click.stop>
                                    <el-button type="text" size="small" @click="editPackage(pkg)" title="编辑">
                                        <i class="el-icon-edit"></i>
                                    </el-button>
                                    <el-button type="text" size="small" @click="deletePackage(pkg)"
                                        style="color: #f56c6c;" title="删除">
                                        <i class="el-icon-delete"></i>
                                    </el-button>
                                </div>
                            </div>
                        </div>


                    </div>

                    <!-- 右侧内容面板 -->
                    <div class="right-panel">
                        <!-- 未选中套餐时的提示 -->
                        <div v-if="!currentPackage" class="no-package-selected">
                            <el-empty description="请先选择套餐">
                                <template slot="description">
                                    <p>请从左侧套餐列表中选择一个套餐，然后开始配置指标权重</p>
                                </template>
                            </el-empty>
                        </div>

                        <!-- 已选中套餐时显示的内容 -->
                        <el-tabs v-else v-model="activeTab" type="border-card" style="height: 100%;">
                            <!-- 第一个Tab：指标选择和权重设置 -->
                            <el-tab-pane label="指标配置" name="indicators" style="height: 100%;">
                                <div style="display: flex; height: 100%; gap: 20px;">
                                    <!-- 指标库 -->
                                    <div class="indicator-library" style="flex: 1;">
                                        <div class="panel-header">
                                            <h3>指标库</h3>
                                        </div>
                                        <div class="panel-content">
                                            <div v-for="indicator in indicatorLibrary" :key="indicator.id"
                                                class="indicator-item"
                                                :class="{ 'selected-major': isSelectedMajor(indicator.id) }">
                                                <div class="indicator-header">
                                                    <div class="indicator-title">
                                                        <el-checkbox :value="isSelectedMajor(indicator.id)"
                                                            @change="toggleMajorIndicator(indicator, $event)">
                                                        </el-checkbox>
                                                        <div class="indicator-name">
                                                            <div class="chinese-name">{{ indicator.chineseName }}</div>
                                                            <div class="english-name">{{ indicator.englishName }}</div>
                                                        </div>
                                                    </div>
                                                    <div class="indicator-actions">
                                                        <span style="font-size: 12px; color: #606266;">权重:</span>
                                                        <el-input-number :value="getMajorWeightValue(indicator.id)"
                                                            @change="updateMajorWeight(indicator.id, $event)"
                                                            class="weight-input" :min="0" :max="100" :precision="1"
                                                            size="mini" controls-position="right" placeholder="0">
                                                        </el-input-number>
                                                        <span
                                                            style="margin-left: 2px; font-size: 12px; color: #606266;">%</span>
                                                    </div>
                                                </div>
                                                <div class="sub-indicators"
                                                    v-if="indicator.children && indicator.children.length > 0 && isSelectedMajor(indicator.id)">
                                                    <div v-for="subIndicator in indicator.children"
                                                        :key="subIndicator.id" class="sub-indicator-item"
                                                        :class="{ 'selected-sub': isSelectedSub(subIndicator.id) }">
                                                        <div style="display: flex; align-items: center; gap: 10px;">
                                                            <el-checkbox :value="isSelectedSub(subIndicator.id)"
                                                                @change="toggleSubIndicator(indicator.id, subIndicator, $event)">
                                                            </el-checkbox>
                                                            <div class="indicator-name">
                                                                <div class="chinese-name">{{ subIndicator.chineseName }}
                                                                </div>
                                                                <div class="english-name">{{ subIndicator.englishName }}
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="indicator-actions"
                                                            style="display: flex; align-items: center; gap: 5px;">
                                                            <span style="font-size: 12px; color: #606266;">权重:</span>
                                                            <el-input-number :value="getSubWeightValue(subIndicator.id)"
                                                                @change="updateSubWeight(subIndicator.id, $event)"
                                                                class="weight-input" :min="0" :max="100" :precision="1"
                                                                size="mini" controls-position="right" placeholder="0">
                                                            </el-input-number>
                                                            <span
                                                                style="margin-left: 2px; font-size: 12px; color: #606266;">%</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 权重汇总信息 -->
                                    <div class="weight-summary-panel" style="flex: 1;">
                                        <div class="panel-header">
                                            <h3>权重汇总 ({{ selectedMajorCount }}个大类, {{ selectedSubCount }}个小类)</h3>
                                        </div>
                                        <div class="panel-content" style="padding: 30px;">
                                            <el-empty v-if="selectedIndicators.length === 0" description="暂无选择指标">
                                                <template slot="description">
                                                    <p>请从左侧指标库中选择相关指标</p>
                                                </template>
                                            </el-empty>
                                            <div v-else class="weight-summary-content">
                                                <div class="weight-item">
                                                    <span>一级指标权重总计:</span>
                                                    <span
                                                        :class="majorWeightTotal === 100 ? 'weight-valid' : 'weight-warning'">
                                                        {{ majorWeightTotal }}%
                                                    </span>
                                                </div>
                                                <div v-for="major in selectedIndicators" :key="'weight-' + major.id"
                                                    class="weight-item"
                                                    v-if="major.selectedSubs && major.selectedSubs.length > 0">
                                                    <span>{{ major.chineseName }} 二级权重:</span>
                                                    <span
                                                        :class="getSubWeightTotal(major.id) === 100 ? 'weight-valid' : 'weight-warning'">
                                                        {{ getSubWeightTotal(major.id) }}%
                                                    </span>
                                                </div>
                                                <div class="weight-item weight-total">
                                                    <span>权重配置状态:</span>
                                                    <span :class="isWeightValid ? 'weight-valid' : 'weight-warning'">
                                                        {{ isWeightValid ? '✓ 配置完成' : '⚠ 需要调整' }}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="action-bar" v-if="selectedIndicators.length > 0">
                                            <div>
                                                <el-button size="small" @click="clearAll">清空所有</el-button>
                                            </div>
                                            <div>
                                                <el-button type="primary" size="small" @click="savePackage"
                                                    :disabled="!isWeightValid || !currentPackage || !currentPackage.name.trim()">
                                                    保存套餐
                                                </el-button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </el-tab-pane>

                            <!-- 第二个Tab：用户清单设置 -->
                            <el-tab-pane label="用户管理" name="users">
                                <div class="user-management">
                                    <div class="panel-content">
                                        <div class="user-actions">
                                            <el-button type="primary" @click="showAddUserDialog"
                                                :disabled="!currentPackage" size="small">
                                                添加用户
                                            </el-button>
                                            <el-button type="warning" @click="removeSelectedUsers"
                                                :disabled="selectedUserIds.length === 0" size="small">
                                                移除选中
                                            </el-button>
                                        </div>

                                        <el-table :data="assignedUsers" @selection-change="handleUserSelectionChange"
                                            class="user-table" height="400">
                                            <el-table-column type="selection" width="55"></el-table-column>
                                            <el-table-column prop="id" label="工号" width="80"></el-table-column>
                                            <el-table-column prop="name" label="姓名" width="100"></el-table-column>
                                            <el-table-column prop="department" label="BU" min-width="180">
                                                <template slot-scope="scope">
                                                    <div style="font-size: 12px; line-height: 1.4;">
                                                        {{ scope.row.department }}
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="position" label="职位" min-width="180">
                                                <template slot-scope="scope">
                                                    <div style="font-size: 12px;">
                                                        {{ scope.row.position }}
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="division" label="Division" min-width="180">
                                                <template slot-scope="scope">
                                                    <div style="font-size: 12px; color: #606266;">
                                                        {{ scope.row.division }}
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="addTime" label="添加时间" width="150"></el-table-column>
                                            <el-table-column label="操作" width="100">
                                                <template slot-scope="scope">
                                                    <el-button type="text" size="small"
                                                        @click="removeUser(scope.row.id)" style="color: #f56c6c;">
                                                        移除
                                                    </el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </div>
            </div>
        </div>

        <!-- 新建套餐对话框 -->
        <el-dialog title="新建指标套餐" :visible.sync="createPackageDialogVisible" width="500px">
            <el-form :model="packageForm" ref="packageForm" :rules="packageRules" label-width="80px">
                <el-form-item label="套餐名称" prop="name">
                    <el-input v-model="packageForm.name" placeholder="请输入套餐名称"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sortOrder">
                    <el-input-number v-model="packageForm.sortOrder" :min="1" :max="999" placeholder="排序号"
                        style="width: 100%;"></el-input-number>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="packageForm.remarks" placeholder="请输入套餐说明或备注"
                        :rows="3"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="createPackageDialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="createPackage" size="small">创建</el-button>
            </div>
        </el-dialog>

        <!-- 编辑套餐对话框 -->
        <el-dialog title="编辑指标套餐" :visible.sync="editPackageDialogVisible" width="500px">
            <el-form :model="packageForm" ref="editPackageForm" :rules="packageRules" label-width="80px">
                <el-form-item label="套餐名称" prop="name">
                    <el-input v-model="packageForm.name" placeholder="请输入套餐名称"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sortOrder">
                    <el-input-number v-model="packageForm.sortOrder" :min="1" :max="999" placeholder="排序号"
                        style="width: 100%;"></el-input-number>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="packageForm.remarks" placeholder="请输入套餐说明或备注"
                        :rows="3"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editPackageDialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="updatePackage" size="small">保存</el-button>
            </div>
        </el-dialog>

        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="1000px">
            <div style="margin-bottom: 15px; display: flex; align-items: center;">
                <el-input placeholder="输入工号或姓名搜索" v-model="userSearchKeyword" size="small" style="width: 300px;">
                    <i slot="prefix" class="el-icon-search" style="line-height: 32px;"></i>
                </el-input>
                <span style="margin-left: 15px; color: #666; font-size: 12px;">
                    已选择 {{ selectedUsersToAdd.length }} 人
                </span>
            </div>

            <el-table :data="filteredAvailableUsers" @selection-change="handleUserSelectionForAdd" height="400"
                size="small">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="id" label="工号" width="80"></el-table-column>
                <el-table-column prop="name" label="姓名" width="100"></el-table-column>
                <el-table-column prop="department" label="BU" min-width="180">
                    <template slot-scope="scope">
                        <div style="font-size: 12px; line-height: 1.4;">
                            {{ scope.row.department }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="position" label="职位" min-width="180">
                    <template slot-scope="scope">
                        <div style="font-size: 12px;">
                            {{ scope.row.position }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="division" label="Division" min-width="180">
                    <template slot-scope="scope">
                        <div style="font-size: 12px; color: #606266;">
                            {{ scope.row.division }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="isUserAssigned(scope.row.id)" size="mini" type="info">已添加</el-tag>
                        <span v-else style="color: #67c23a; font-size: 12px;">可添加</span>
                    </template>
                </el-table-column>
            </el-table>

            <div slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="addSelectedUsers" :disabled="selectedUsersToAdd.length === 0"
                    size="small">
                    添加选中用户 ({{ selectedUsersToAdd.length }})
                </el-button>
            </div>
        </el-dialog>
    </div>

    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="kpi-indicator-data.js"></script>
    <script src="user-data.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    activeTab: 'indicators',
                    packageList: [],
                    currentPackage: null,
                    createPackageDialogVisible: false,
                    editPackageDialogVisible: false,
                    editingPackage: null,
                    packageForm: {
                        name: '',
                        sortOrder: 1,
                        remarks: ''
                    },
                    packageRules: {
                        name: [
                            { required: true, message: '请输入套餐名称', trigger: 'blur' }
                        ],
                        sortOrder: [
                            { required: true, message: '请输入排序号', trigger: 'blur' }
                        ]
                    },
                    indicatorLibrary: [],
                    selectedIndicators: [],
                    assignedUsers: [],
                    selectedUserIds: [],
                    addUserDialogVisible: false,
                    availableUsers: [], // Will be loaded from user-data.js
                    selectedUsersToAdd: [],
                    userSearchKeyword: ''
                }
            },
            computed: {
                sortedPackageList() {
                    return this.packageList.slice().sort((a, b) => a.sortOrder - b.sortOrder);
                },
                filteredAvailableUsers() {
                    if (!this.userSearchKeyword) {
                        return this.availableUsers;
                    }
                    const keyword = this.userSearchKeyword.toLowerCase();
                    return this.availableUsers.filter(user =>
                        user.id.toLowerCase().includes(keyword) ||
                        user.name.toLowerCase().includes(keyword) ||
                        user.department.toLowerCase().includes(keyword) ||
                        user.position.toLowerCase().includes(keyword)
                    );
                },
                selectedMajorCount() {
                    return this.selectedIndicators.length;
                },
                selectedSubCount() {
                    return this.selectedIndicators.reduce((count, major) => {
                        return count + (major.selectedSubs ? major.selectedSubs.length : 0);
                    }, 0);
                },
                majorWeightTotal() {
                    return Math.round(this.selectedIndicators.reduce((total, major) => {
                        return total + (parseFloat(major.weight) || 0);
                    }, 0) * 100) / 100;
                },
                isWeightValid() {
                    if (this.majorWeightTotal !== 100) return false;

                    for (const major of this.selectedIndicators) {
                        if (major.selectedSubs && major.selectedSubs.length > 0) {
                            const subTotal = this.getSubWeightTotal(major.id);
                            if (subTotal !== 100) return false;
                        }
                    }
                    return true;
                }
            },
            mounted() {
                this.loadIndicatorLibrary();
                this.loadPackageList();
                this.loadUserDataFromJS(); // Load user data from user-data.js
            },
            watch: {
                currentPackage(newPackage) {
                    if (newPackage) {
                        this.loadPackageData(newPackage.id);
                    } else {
                        this.selectedIndicators = [];
                        this.assignedUsers = [];
                    }
                }
            },
            methods: {
                loadIndicatorLibrary() {
                    // Load indicators from kpi-indicator-data.js
                    if (typeof IndicatorDataManager !== 'undefined') {
                        // The data from IndicatorDataManager is already in tree structure
                        this.indicatorLibrary = IndicatorDataManager.loadIndicatorData();
                    } else {
                        // Fallback to default data if kpi-indicator-data.js is not available
                        this.indicatorLibrary = [
                            {
                                id: '1', chineseName: '工作绩效', englishName: 'Work Performance',
                                children: [
                                    { id: '1-1', parentId: '1', chineseName: '任务完成率', englishName: 'Task Completion Rate' },
                                    { id: '1-2', parentId: '1', chineseName: '工作质量', englishName: 'Work Quality' }
                                ]
                            },
                            {
                                id: '2', chineseName: '团队协作', englishName: 'Team Collaboration',
                                children: [
                                    { id: '2-1', parentId: '2', chineseName: '沟通效果', englishName: 'Communication Effectiveness' }
                                ]
                            },
                            { id: '3', chineseName: '学习发展', englishName: 'Learning & Development', children: [] }
                        ];
                    }
                },

                // Load user data from user-data.js
                loadUserDataFromJS() {
                    if (typeof userList !== 'undefined' && userList.length > 0) {
                        // Transform user data to match the expected format
                        this.availableUsers = userList.map(user => ({
                            id: user.code, // Use employee code as ID
                            name: user.name,
                            department: user.bu, // Use BU as department
                            position: user.jobFamily, // Use jobFamily as position
                            division: user.division,
                            location: user.locatiom, // Note: original data has typo 'locatiom'
                            hrType: user.hrType,
                            dateJoin: user.dateJoin,
                            originalId: user.id // Keep original ID for reference
                        }));
                        console.log(`Loaded ${this.availableUsers.length} users from user-data.js`);
                    } else {
                        console.warn('userList not found in user-data.js, using fallback data');
                        // Fallback to a few default users if user-data.js is not available
                        this.availableUsers = [
                            { id: 'U001', name: '示例用户', department: '人力资源部', position: 'HR专员' }
                        ];
                    }
                },

                loadPackageList() {
                    const packages = [];
                    for (let i = 0; i < localStorage.length; i++) {
                        const key = localStorage.key(i);
                        if (key && key.startsWith('indicatorPackage_')) {
                            try {
                                const packageData = JSON.parse(localStorage.getItem(key));
                                packages.push({
                                    id: key,
                                    name: packageData.name,
                                    sortOrder: packageData.sortOrder || 1,
                                    remarks: packageData.remarks || '',
                                    updateTime: packageData.updateTime
                                });
                            } catch (e) {
                                console.warn('Failed to parse package:', key);
                            }
                        }
                    }
                    this.packageList = packages;
                },
                showCreatePackageDialog() {
                    this.packageForm = {
                        name: '',
                        sortOrder: this.packageList.length + 1,
                        remarks: ''
                    };
                    this.createPackageDialogVisible = true;
                },
                createPackage() {
                    this.$refs.packageForm.validate((valid) => {
                        if (valid) {
                            // 检查套餐名称是否已存在
                            if (this.packageList.some(pkg => pkg.name === this.packageForm.name)) {
                                this.$message.warning('该套餐名称已存在');
                                return;
                            }

                            const packageId = 'indicatorPackage_' + Date.now();
                            const packageData = {
                                name: this.packageForm.name,
                                sortOrder: this.packageForm.sortOrder,
                                remarks: this.packageForm.remarks,
                                indicators: [],
                                updateTime: new Date().toISOString()
                            };

                            localStorage.setItem(packageId, JSON.stringify(packageData));
                            this.loadPackageList();

                            // 自动选中新创建的套餐
                            this.currentPackage = {
                                id: packageId,
                                name: packageData.name,
                                sortOrder: packageData.sortOrder,
                                remarks: packageData.remarks,
                                updateTime: packageData.updateTime
                            };

                            this.createPackageDialogVisible = false;
                            this.$message.success('套餐创建成功');
                        }
                    });
                },
                selectPackage(pkg) {
                    this.currentPackage = pkg;
                },
                editPackage(pkg) {
                    this.editingPackage = pkg;
                    this.packageForm = {
                        name: pkg.name,
                        sortOrder: pkg.sortOrder,
                        remarks: pkg.remarks || ''
                    };
                    this.editPackageDialogVisible = true;
                },
                updatePackage() {
                    this.$refs.editPackageForm.validate((valid) => {
                        if (valid) {
                            // 检查套餐名称是否已存在（排除当前编辑的套餐）
                            if (this.packageList.some(pkg => pkg.name === this.packageForm.name && pkg.id !== this.editingPackage.id)) {
                                this.$message.warning('该套餐名称已存在');
                                return;
                            }

                            // 更新套餐数据
                            const packageData = {
                                name: this.packageForm.name,
                                sortOrder: this.packageForm.sortOrder,
                                remarks: this.packageForm.remarks,
                                indicators: [],
                                updateTime: new Date().toISOString()
                            };

                            // 如果是当前选中的套餐，保留现有的指标数据
                            if (this.currentPackage && this.currentPackage.id === this.editingPackage.id) {
                                packageData.indicators = this.selectedIndicators;
                            } else {
                                // 加载现有的指标数据
                                try {
                                    const existingData = JSON.parse(localStorage.getItem(this.editingPackage.id));
                                    packageData.indicators = existingData.indicators || [];
                                } catch (e) {
                                    packageData.indicators = [];
                                }
                            }

                            localStorage.setItem(this.editingPackage.id, JSON.stringify(packageData));
                            this.loadPackageList();

                            // 更新当前选中的套餐信息
                            if (this.currentPackage && this.currentPackage.id === this.editingPackage.id) {
                                this.currentPackage = {
                                    id: this.editingPackage.id,
                                    name: packageData.name,
                                    sortOrder: packageData.sortOrder,
                                    remarks: packageData.remarks,
                                    updateTime: packageData.updateTime
                                };
                            }

                            this.editPackageDialogVisible = false;
                            this.$message.success('套餐更新成功');
                        }
                    });
                },
                deletePackage(pkg) {
                    this.$confirm(`确定要删除套餐“${pkg.name}”吗？删除后将无法恢复。`, '删除确认', {
                        confirmButtonText: '确定删除',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        // 删除套餐数据
                        localStorage.removeItem(pkg.id);

                        // 删除关联的用户数据
                        const userKey = `packageUsers_${pkg.id}`;
                        localStorage.removeItem(userKey);

                        // 如果是当前选中的套餐，清除选中状态
                        if (this.currentPackage && this.currentPackage.id === pkg.id) {
                            this.currentPackage = null;
                            this.selectedIndicators = [];
                            this.assignedUsers = [];
                        }

                        this.loadPackageList();
                        this.$message.success('套餐已删除');
                    }).catch(() => {
                        // 用户取消删除
                    });
                },
                loadPackageData(packageId) {
                    try {
                        const packageData = JSON.parse(localStorage.getItem(packageId));
                        this.selectedIndicators = packageData.indicators || [];
                        this.loadPackageUsers();
                    } catch (e) {
                        console.warn('Failed to load package data:', e);
                        this.selectedIndicators = [];
                        this.assignedUsers = [];
                    }
                },
                isSelectedMajor(majorId) {
                    return this.selectedIndicators.some(item => item.id === majorId);
                },
                isSelectedSub(subId) {
                    for (const major of this.selectedIndicators) {
                        if (major.selectedSubs && major.selectedSubs.some(sub => sub.id === subId)) {
                            return true;
                        }
                    }
                    return false;
                },
                getMajorWeightValue(majorId) {
                    const major = this.selectedIndicators.find(item => item.id === majorId);
                    return major ? (major.weight || 0) : 0;
                },
                getSubWeightValue(subId) {
                    for (const major of this.selectedIndicators) {
                        if (major.selectedSubs) {
                            const sub = major.selectedSubs.find(s => s.id === subId);
                            if (sub) return (sub.weight || 0);
                        }
                    }
                    return 0;
                },
                getMajorWeight(majorId) {
                    const major = this.selectedIndicators.find(item => item.id === majorId);
                    return major ? (major.weight || 0) : 0;
                },
                getSubWeight(subId) {
                    for (const major of this.selectedIndicators) {
                        if (major.selectedSubs) {
                            const sub = major.selectedSubs.find(s => s.id === subId);
                            if (sub) return (sub.weight || 0);
                        }
                    }
                    return 0;
                },
                getSubWeightTotal(majorId) {
                    const major = this.selectedIndicators.find(item => item.id === majorId);
                    if (!major || !major.selectedSubs) return 0;
                    return Math.round(major.selectedSubs.reduce((total, sub) => {
                        return total + (parseFloat(sub.weight) || 0);
                    }, 0) * 100) / 100;
                },
                toggleMajorIndicator(indicator, selected) {
                    if (selected) {
                        const newMajor = {
                            ...indicator,
                            weight: 0,
                            selectedSubs: []
                        };
                        this.selectedIndicators.push(newMajor);
                    } else {
                        this.selectedIndicators = this.selectedIndicators.filter(item => item.id !== indicator.id);
                    }
                },
                toggleSubIndicator(majorId, subIndicator, selected) {
                    const major = this.selectedIndicators.find(item => item.id === majorId);
                    if (!major) return;

                    if (selected) {
                        if (!major.selectedSubs) major.selectedSubs = [];
                        major.selectedSubs.push({
                            ...subIndicator,
                            weight: 0
                        });
                    } else {
                        major.selectedSubs = major.selectedSubs.filter(sub => sub.id !== subIndicator.id);
                    }
                },
                updateMajorWeight(majorId, value) {
                    const major = this.selectedIndicators.find(item => item.id === majorId);
                    if (major) {
                        const weight = parseFloat(value) || 0;
                        major.weight = Math.max(0, Math.min(100, weight));
                        this.$forceUpdate();
                    }
                },
                updateSubWeight(subId, value) {
                    for (const major of this.selectedIndicators) {
                        if (major.selectedSubs) {
                            const sub = major.selectedSubs.find(s => s.id === subId);
                            if (sub) {
                                const weight = parseFloat(value) || 0;
                                sub.weight = Math.max(0, Math.min(100, weight));
                                this.$forceUpdate();
                                break;
                            }
                        }
                    }
                },
                removeMajorIndicator(majorId) {
                    this.selectedIndicators = this.selectedIndicators.filter(item => item.id !== majorId);
                },
                removeSubIndicator(majorId, subId) {
                    const major = this.selectedIndicators.find(item => item.id === majorId);
                    if (major && major.selectedSubs) {
                        major.selectedSubs = major.selectedSubs.filter(sub => sub.id !== subId);
                    }
                },
                clearAll() {
                    this.$confirm('确定要清空所有已选指标吗？', '清空确认', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.selectedIndicators = [];
                        this.$message.success('已清空所有指标');
                    });
                },

                savePackage() {
                    if (!this.currentPackage) {
                        this.$message.warning('请先选择套餐');
                        return;
                    }

                    if (!this.isWeightValid) {
                        this.$message.warning('权重配置不正确，请检查后再保存');
                        return;
                    }

                    const packageData = {
                        name: this.currentPackage.name,
                        sortOrder: this.currentPackage.sortOrder,
                        remarks: this.currentPackage.remarks,
                        indicators: this.selectedIndicators,
                        updateTime: new Date().toISOString()
                    };

                    localStorage.setItem(this.currentPackage.id, JSON.stringify(packageData));
                    this.savePackageUsers();

                    this.$message.success('KPI指标套餐已保存');
                },
                // 用户管理相关方法
                showAddUserDialog() {
                    this.selectedUsersToAdd = [];
                    this.userSearchKeyword = '';
                    this.addUserDialogVisible = true;
                },
                isUserAssigned(userId) {
                    return this.assignedUsers.some(user => user.id === userId);
                },
                handleUserSelectionForAdd(selection) {
                    // 过滤掉已经添加的用户
                    this.selectedUsersToAdd = selection.filter(user => !this.isUserAssigned(user.id));
                },
                addSelectedUsers() {
                    if (this.selectedUsersToAdd.length === 0) {
                        this.$message.warning('请选择要添加的用户');
                        return;
                    }

                    // 添加时间戳
                    const usersToAdd = this.selectedUsersToAdd.map(user => ({
                        ...user,
                        addTime: new Date().toLocaleString()
                    }));

                    this.assignedUsers.push(...usersToAdd);
                    this.addUserDialogVisible = false;
                    this.savePackageUsers();

                    this.$message.success(`已成功添加 ${usersToAdd.length} 个用户`);
                },
                removeUser(userId) {
                    this.$confirm('确定要移除该用户吗？', '确认移除', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.assignedUsers = this.assignedUsers.filter(user => user.id !== userId);
                        this.$message.success('用户已移除');
                        this.savePackageUsers();
                    });
                },
                handleUserSelectionChange(selection) {
                    this.selectedUserIds = selection.map(user => user.id);
                },
                removeSelectedUsers() {
                    if (this.selectedUserIds.length === 0) {
                        this.$message.warning('请选择要移除的用户');
                        return;
                    }

                    this.$confirm(`确定要移除选中的${this.selectedUserIds.length}个用户吗？`, '批量移除', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.assignedUsers = this.assignedUsers.filter(user => !this.selectedUserIds.includes(user.id));
                        this.selectedUserIds = [];
                        this.$message.success('选中用户已移除');
                        this.savePackageUsers();
                    });
                },
                savePackageUsers() {
                    if (!this.currentPackage) return;

                    // 保存用户数据到对应的套餐中
                    const userKey = `packageUsers_${this.currentPackage.id}`;
                    localStorage.setItem(userKey, JSON.stringify(this.assignedUsers));
                },
                loadPackageUsers() {
                    if (!this.currentPackage) {
                        this.assignedUsers = [];
                        return;
                    }

                    const userKey = `packageUsers_${this.currentPackage.id}`;
                    const saved = localStorage.getItem(userKey);
                    if (saved) {
                        try {
                            this.assignedUsers = JSON.parse(saved);
                        } catch (e) {
                            console.warn('Failed to parse package users:', e);
                            this.assignedUsers = [];
                        }
                    } else {
                        this.assignedUsers = [];
                    }
                }
            }
        });
    </script>
</body>

</html>